package com.eiisan.web.web.feign;

import com.alibaba.fastjson.JSONObject;
import com.eiisan.core.token.GenerateToken;
import com.eiisan.core.util.api.Result;
import com.eiisan.core.util.twitter.SnowflakeIdUtils;
import com.eiisan.web.feign.PayMentTransacTokenClientApi;
import com.eiisan.web.mapper.PaymentTransactionMapper;
import com.eiisan.web.model.domain.PaymentTransaction;
import com.eiisan.web.model.dto.PayCratePayTokenDto;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author gragonfly
 * @date 2019/7/17
 **/
@RestController
@Api(tags = "API - PayMentTransacTokenFeign")
public class PayMentTransacTokenClient implements PayMentTransacTokenClientApi {
    @Autowired
    private PaymentTransactionMapper paymentTransactionMapper;

    @Autowired
    private GenerateToken generateToken;

    /**
     * 创建支付令牌
     */
    @GetMapping("/cratePayToken")
    public Result<JSONObject> cratePayToken(PayCratePayTokenDto payCratePayTokenDto){
        String orderId = payCratePayTokenDto.getOrderId();
        if (StringUtils.isEmpty(orderId)) {
            return Result.errorRequest("订单号码不能为空!");
        }
        Long payAmount = payCratePayTokenDto.getPayAmount();
        if (payAmount == null) {
            return Result.errorRequest("金额不能为空!");
        }
        Long userId = payCratePayTokenDto.getUserId();
        if (userId == null) {
            return Result.errorRequest("userId不能为空!");
        }
        // 2.将输入插入数据库中 待支付记录
        PaymentTransaction paymentTransaction = new PaymentTransaction();
        paymentTransaction.setOrderId(orderId);
        paymentTransaction.setPayAmount(payAmount);
        paymentTransaction.setUserId(userId);
        // 使用雪花算法 生成全局id
        paymentTransaction.setPaymentId(SnowflakeIdUtils.nextId());
        int result = paymentTransactionMapper.insertPaymentTransaction(paymentTransaction);
        if (!(result > 0)) {
            return Result.fail("系统错误!");
        }
        // 获取主键id
        Long payId = paymentTransaction.getId();
        if (payId == null) {
            return Result.fail("系统错误!");
        }

        // 3.生成对应支付令牌
        String keyPrefix = "pay_";
        String token = generateToken.createToken(keyPrefix, payId + "");
        JSONObject dataResult = new JSONObject();
        dataResult.put("token", token);
        return Result.success(dataResult);
    }

}
